package org.store.dao;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.transaction.annotation.Transactional;
import org.store.domain.Image;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ImageDao extends AbstractDao<Image> {
    @Override
    public Image getById(long id) throws DaoException {
        try {
            return jdbcTemplate.queryForObject("select image_id, data_type, data from image where image_id = ?", MAPPER, id);
        } catch (DataAccessException e) {
            throw new DaoException("Cannot get image with id = " + id, e);
        }
    }

    @Override
    @Transactional
    public Image save(Image image) throws DaoException {
        if (image == null)
            throw new IllegalArgumentException("Image cannot be null");
        try {
            long id = jdbcTemplate.queryForLong("insert into image (data_type, data) values(?,?) returning image_id", image.getType(), image.getArr());
            image.setId(id);
            return image;
        } catch (DataAccessException e) {
            throw new DaoException("Cannot save image with id = " + image.getId(), e);
        }
    }

    @Override
    public boolean delete(Image image) throws DaoException {
        return false;
    }

    @Override
    public Image saveOrUpdate(Image image) throws DaoException {
        return null;
    }

    @Override
    public List<Image> saveAll(List<Image> e) throws DaoException {
        return new ArrayList<>();
    }

    @Override
    public boolean isExists(long id) throws DaoException {
        try {
            return jdbcTemplate.queryForLong("select count(*) from image where image_id = ?", id) > 0;
        } catch (DataAccessException e) {
            throw new DaoException("Cannot get image with id = " + id, e);
        }
    }

    private static final RowMapper<Image> MAPPER = new RowMapper<Image>() {
        public Image mapRow(ResultSet rs, int rowNum) throws SQLException {
            Image image = new Image(rs.getString("data_type"), rs.getBytes("data"));
            image.setId(rs.getLong("image_id"));
            return image;
        }
    };
}
